package com.talent.jiwen.training;

import android.content.Context;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.wrongbook.StartPracticeBean;
import com.talent.jiwen.http.result.tiku.DifficultyBean;
import com.talent.jiwen.http.result.tiku.GradeBean;
import com.talent.jiwen.http.result.tiku.QuestionType;
import com.talent.jiwen.http.result.tiku.SubjectBean;
import com.talent.jiwen.http.result.tiku.VersionBean;
import com.talent.jiwen.training.data.IdNameBean;
import com.talent.jiwen.ui.widgets.TrainingSelectLayoutPop;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.MyToast;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;
import com.talent.jiwen.util.Validators;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

public class TrainingSelectActivity extends BaseActivity {
    @BindView(R.id.selectSubjectTv)
    TextView selectSubjectTv;
    @BindView(R.id.selectSubjectLayout)
    RelativeLayout selectSubjectLayout;
    @BindView(R.id.selectVersionTv)
    TextView selectVersionTv;
    @BindView(R.id.selectVersionLayout)
    RelativeLayout selectVersionLayout;
    @BindView(R.id.selectGradeTv)
    TextView selectGradeTv;
    @BindView(R.id.selectGradeLayout)
    RelativeLayout selectGradeLayout;
    @BindView(R.id.selectChapterTv)
    TextView selectChapterTv;
    @BindView(R.id.selectChapterLayout)
    RelativeLayout selectChapterLayout;
    @BindView(R.id.selectQuestionTypeTv)
    TextView selectQuestionTypeTv;
    @BindView(R.id.selectQuestionTypeLayout)
    RelativeLayout selectQuestionTypeLayout;
    @BindView(R.id.selectDifficultyTv)
    TextView selectDifficultyTv;
    @BindView(R.id.selectDifficultyLayout)
    RelativeLayout selectDifficultyLayout;
    @BindView(R.id.selectUnderStandTv)
    TextView selectUnderStandTv;
    @BindView(R.id.selectUnderStandLayout)
    RelativeLayout selectUnderStandLayout;
    @BindView(R.id.remarkEt)
    EditText remarkEt;
    @BindView(R.id.remarkLayout)
    LinearLayout remarkLayout;
    @BindView(R.id.scrollView)
    ScrollView scrollView;
    @BindView(R.id.sureBtn)
    Button sureBtn;

    private static final String PARAM_TYPE = "param.type";
    private static final String PARAM_IMG_INFO_LIST = "param.img.info.list";
    public static final int TYPE_TIKU_PRACTICE = 0; //题库训练
    public static final int TYPE_ERROR_BOOK = 1; // 错题集

    private static final int PICK_TYPE_SUBJECT = 1;//选择学科
    private static final int PICK_TYPE_VERSION = 2;//选择教材版本
    private static final int PICK_TYPE_GRADE = 3;//选择年级
    private static final int PICK_TYPE_CHAPTER = 4;//选择内容章节
    private static final int PICK_TYPE_QUESTION = 5;//选择题型
    private static final int PICK_TYPE_DIFFICUTY = 6;//选择难度
    private static final int PICK_TYPE_UNDERSTAND = 7;//选择掌握程度


    private IdNameBean subjectIdNameBean = null;//选中的教材
    private IdNameBean versionIdNameBean = null;//选中的版本
    private IdNameBean gradeIdNameBean = null;//选中的年级
    private IdNameBean chapterIdNameBean = null;//选中的章节
    private IdNameBean questionTypeIdNameBean = null;//选中的题目类型
    private IdNameBean difficultyIdNameBean = null;//选中的难度
    private IdNameBean underStandIdNameBean = new IdNameBean(1 , "不懂");//选中的掌握程度

    private String NEGATIVE = "";
    private int type;
    private String imgJsonStr;

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_training_select;
    }

    @Override
    public String titleName() {
        return getString(R.string.training_select);
    }

    @Override
    protected void initData() {

        registEventBus();

        NEGATIVE = getString(R.string.not_choose);
        type = getIntent().getIntExtra(PARAM_TYPE, 0);
        if (type == TYPE_TIKU_PRACTICE) {
            //隐藏掌握程度和备注信息
            selectUnderStandLayout.setVisibility(View.GONE);
            remarkLayout.setVisibility(View.GONE);
//            tv_toolbar_title.setText("题库训练");
//            sureBtn.setText("开始做题");
        } else {
            selectUnderStandLayout.setVisibility(View.VISIBLE);
            remarkLayout.setVisibility(View.VISIBLE);
            imgJsonStr = getIntent().getStringExtra(PARAM_IMG_INFO_LIST);
//            tv_toolbar_title.setText("添加标签");
//            sureBtn.setText("完成");

            remarkEt.addTextChangedListener(new TextWatcher() {
                @Override
                public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                }

                @Override
                public void afterTextChanged(Editable editable) {
                    String content = remarkEt.getText().toString();
                    if (content.length() > 20) {
                        MyToast.show(TrainingSelectActivity.this, "只能输入20字以内的内容");
                        remarkEt.setText(content.substring(0, 19));
                        remarkEt.setSelection(remarkEt.getText().toString().length());
                    }
                }
            });
        }
    }

    @Subscribe
    public void onGetChapterList(IdNameBean idNameBean) {
        chapterIdNameBean = idNameBean;
        selectChapterTv.setText(getString(R.string.already_choose));
        //将内容之后的选项清空
        questionTypeIdNameBean = null;
        selectQuestionTypeTv.setText(NEGATIVE);
        difficultyIdNameBean = null;
        selectDifficultyTv.setText(NEGATIVE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    @OnClick({R.id.selectSubjectLayout, R.id.selectVersionLayout, R.id.selectGradeLayout, R.id.selectChapterLayout, R.id.selectQuestionTypeLayout, R.id.selectDifficultyLayout, R.id.sureBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.selectSubjectLayout:
                getSubjectList();
                break;
            case R.id.selectVersionLayout:
                if (null == subjectIdNameBean) {
                    showToast(getString(R.string.please_choose_subject));
                } else {
                    getVersionList();
                }
                break;
            case R.id.selectGradeLayout:
                if (null == versionIdNameBean) {
                    showToast(getString(R.string.please_choose_version));
                } else {
                    getGradeList();
                }
                break;
            case R.id.selectChapterLayout:
                if (selectGradeTv.getText().toString().equals(NEGATIVE)) {
                    showToast(getString(R.string.please_choose_grade));
                } else {
                    SelectChapterActivity.startSelectChapterActivity(mContext, gradeIdNameBean.getId() + "", chapterIdNameBean);
                }
                break;
            case R.id.selectQuestionTypeLayout:
                if (selectChapterTv.getText().toString().equals(NEGATIVE)) {
                    showToast(getString(R.string.please_choose_chapter));
                } else {
                    getQuestionTypeList();
                }
                break;
            case R.id.selectDifficultyLayout:
                if (selectQuestionTypeTv.getText().toString().equals(NEGATIVE)) {
                    showToast(getString(R.string.please_choose_question_type));
                } else {
                    getDifficultyList();
                }
                break;
            case R.id.sureBtn:
                if (selectDifficultyTv.getText().toString().equals(NEGATIVE)) {
                    showToast(getString(R.string.please_check_choose));
                } else {
                    if (type == TYPE_TIKU_PRACTICE) {
                        startPractice();
                    } else {
//                        saveErrorImg();
                    }
                }
                break;
        }
    }


    /**
     * 开始题库训练
     */
    private void startPractice() {
        Map<String, String> map = new HashMap<>();
        map.put("studentId", SPUtil.stringOut(SPConstant.USER_ID));
//        map.put("schoolId", SPUtil.stringOut(SPConstant.SCHOOL_ID));
        //////////////////////////////新添加///////////////////////////////////
        map.put("subjectId", subjectIdNameBean.getId() + "");
        map.put("subjectName", subjectIdNameBean.getName());
        map.put("categoryId", versionIdNameBean.getId() + "");
        map.put("categoryName", versionIdNameBean.getName());
        map.put("gradeId", gradeIdNameBean.getId() + "");
        map.put("gradeName", gradeIdNameBean.getName());
        map.put("chapterId", chapterIdNameBean.getIdStr());
        map.put("chapterName", chapterIdNameBean.getName());
        map.put("questionTypeId", questionTypeIdNameBean.getId() + "");
        map.put("questionTypeName", questionTypeIdNameBean.getName());
        map.put("difficultyLevelId", difficultyIdNameBean.getId() + "");
        map.put("difficultyLevelName", difficultyIdNameBean.getName());
        map.put("hardTrainingStatus", Constant.TRAINING_NORMAL);

        Observable observable = ApiFactory.getEducationApiSingleton().studentStartHomeworkPractice(SPUtil.stringOut(SPConstant.TOKEN), map);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<StartPracticeBean>(mContext) {
                    @Override
                    protected void _onNext(StartPracticeBean startPracticeBean) {
                        String practiceWorkId = startPracticeBean.getLogInfo().getId();
                        MyToast.show(TrainingSelectActivity.this,"开始训练");
                    }

                    @Override
                    protected void _onError(String message) {
                        showToast(message);
                    }
                }
                , ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }


    /**
     * 获取学科信息
     */
    public void getSubjectList() {
        String grade;
        if (SPConstant.isMidSchool()) {
            grade = Constant.TIKU_MIDDLE_GRADE;
        } else {
            grade = Constant.TIKU_PRIMARY_GRADE;
        }
        Observable observable = ApiFactory.getTiKuApiSingleton().getSubject(grade);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<SubjectBean>>(mContext) {
            @Override
            protected void _onNext(List<SubjectBean> listBean) {
                List<IdNameBean> pickList = new ArrayList<>();
                for (SubjectBean bean : listBean) {
                    pickList.add(new IdNameBean(bean.getKecen_id(), bean.getKecen_name()));
                }
                showWheelPicker(pickList, subjectIdNameBean, PICK_TYPE_SUBJECT);
            }

            @Override
            protected void _onError(String message) {
                MyToast.show(TrainingSelectActivity.this, message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

    /**
     * 获取教材版本
     */
    private void getVersionList() {
        Observable observable = ApiFactory.getTiKuApiSingleton().getBanben(subjectIdNameBean.getId() + "");

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<VersionBean>>(mContext) {
                    @Override
                    protected void _onNext(List<VersionBean> textBookBeen) {
                        List<IdNameBean> versionList = new ArrayList<>();
                        for (VersionBean bean : textBookBeen) {
                            versionList.add(new IdNameBean(bean.getJlid(), bean.getBanben()));
                        }
                        layoutPicker(versionList, versionIdNameBean, PICK_TYPE_VERSION, "请选择教材版本");
                    }

                    @Override
                    protected void _onError(String message) {
                        showToast(message);
                    }
                },
                ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }


    /**
     * 获取年级列表
     */
    private void getGradeList() {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("kecen_id", subjectIdNameBean.getId() + "");
        hashMap.put("banben", versionIdNameBean.getId() + "");
        Observable observable = ApiFactory.getTiKuApiSingleton().getGrade(hashMap);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<GradeBean>>(mContext) {
                    @Override
                    protected void _onNext(List<GradeBean> selectGradeBean) {
                        List<IdNameBean> gradeList = new ArrayList<>();
                        for (GradeBean data : selectGradeBean) {
                            gradeList.add(new IdNameBean(data.getZsd_id(), data.getZsd_name()));
                        }

                        showWheelPicker(gradeList, gradeIdNameBean, PICK_TYPE_GRADE);
                    }

                    @Override
                    protected void _onError(String message) {
                        showToast(message);
                    }
                }
                , ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }


    /**
     * 获取问题类型列表
     */
    public void getQuestionTypeList() {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("kecen_id", subjectIdNameBean.getId() + "");
        hashMap.put("zjids", chapterIdNameBean.getIdStr());
        Observable observable = ApiFactory.getTiKuApiSingleton().getQuestionType(hashMap);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<QuestionType>>(mContext) {
                    @Override
                    protected void _onNext(List<QuestionType> questionTypes) {
                        List<IdNameBean> qustionTypeList = new ArrayList<>();
                        for (QuestionType questionType : questionTypes) {
                            qustionTypeList.add(new IdNameBean(questionType.getTixin_id(), questionType.getTixinmin()));
                        }
                        layoutPicker(qustionTypeList, questionTypeIdNameBean, PICK_TYPE_QUESTION, "请选择题目类型");
                    }

                    @Override
                    protected void _onError(String message) {
                        showToast(message);
                    }
                },
                ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }

    /**
     * 获取难度列表
     */
    public void getDifficultyList() {
        Map<String, String> hashMap = new HashMap<>();
        hashMap.put("kecen_id", subjectIdNameBean.getId() + "");
        hashMap.put("zjids", chapterIdNameBean.getIdStr());
        hashMap.put("titin_id", questionTypeIdNameBean.getId() + "");
        Observable observable = ApiFactory.getTiKuApiSingleton().getDifficulty(hashMap);

        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<List<DifficultyBean>>(mContext) {
                    @Override
                    protected void _onNext(List<DifficultyBean> difficultyBean) {
                        List<IdNameBean> difficultyList = new ArrayList<>();
                        for (DifficultyBean data : difficultyBean) {
                            if (!Validators.isEmpty(data.getLandu_name())) {
                                difficultyList.add(new IdNameBean(data.getLandu_id(), data.getLandu_name()));
                            }
                        }

                        layoutPicker(difficultyList, difficultyIdNameBean, PICK_TYPE_DIFFICUTY, "请选择题目难度");
                    }

                    @Override
                    protected void _onError(String message) {
                        showToast(message);
                    }
                },
                ActivityLifeCycleEvent.DESTROY, lifecycleSubject, true);
    }


    /**
     * 滚轮选择
     *
     * @param pickerList
     * @param selectItem
     * @param pickType
     */
    private void showWheelPicker(final List<IdNameBean> pickerList, final IdNameBean selectItem, final int pickType) {
        List<String> showList = new ArrayList<>();
        int selectPosition = 0;
        for (int i = 0; i < pickerList.size(); i++) {
            showList.add(pickerList.get(i).getName());
            if (null != selectItem){
                if (selectItem.getId() == pickerList.get(i).getId()) {
                    selectPosition = i;
                }
            }
        }
        OptionsPickerView pvOptions = new OptionsPickerBuilder(TrainingSelectActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                if (pickType == PICK_TYPE_SUBJECT) {
                    //选择学科
                    subjectIdNameBean = pickerList.get(options1);
                    selectSubjectTv.setText(subjectIdNameBean.getName());
                    //选择学科之后，将学科之后的选项清空
                    versionIdNameBean = null;
                    selectVersionTv.setText(NEGATIVE);
                    gradeIdNameBean = null;
                    selectGradeTv.setText(NEGATIVE);
                    chapterIdNameBean = null;
                    selectChapterTv.setText(NEGATIVE);
                    questionTypeIdNameBean = null;
                    selectQuestionTypeTv.setText(NEGATIVE);
                    difficultyIdNameBean = null;
                    selectDifficultyTv.setText(NEGATIVE);
                } else if (pickType == PICK_TYPE_GRADE) {
                    //选择年级
                    gradeIdNameBean = pickerList.get(options1);
                    selectGradeTv.setText(gradeIdNameBean.getName());
                    //将年级之后的选项清空
                    chapterIdNameBean = null;
                    selectChapterTv.setText(NEGATIVE);
                    questionTypeIdNameBean = null;
                    selectQuestionTypeTv.setText(NEGATIVE);
                    difficultyIdNameBean = null;
                    selectDifficultyTv.setText(NEGATIVE);
                }
            }
        }).build();
        pvOptions.setPicker(showList);

        if (null != selectItem) {
            pvOptions.setSelectOptions(selectPosition);
        }
        pvOptions.show();
    }


    /**
     * 显示layout选择器
     *
     * @param pickList
     * @param selectItem
     * @param pickType
     */
    private void layoutPicker(List<IdNameBean> pickList, final IdNameBean selectItem, final int pickType, String title) {
        final TrainingSelectLayoutPop selectLayoutPop = new TrainingSelectLayoutPop(TrainingSelectActivity.this);

        if (null != selectItem) {
            for (IdNameBean data : pickList) {
                if (data.getId() == selectItem.getId()) {
                    data.setSelected(true);
                } else {
                    data.setSelected(false);
                }
            }
        }
        selectLayoutPop.setData(title, pickList, new TrainingSelectLayoutPop.OnTikuSelectItemClickListener() {
            @Override
            public void itemClick(IdNameBean idNameBean) {
                if (pickType == PICK_TYPE_VERSION) {
                    //选择版本
                    versionIdNameBean = idNameBean;
                    selectVersionTv.setText(idNameBean.getName());
                    //将版本之后的选项清空
                    gradeIdNameBean = null;
                    selectGradeTv.setText(NEGATIVE);
                    chapterIdNameBean = null;
                    selectChapterTv.setText(NEGATIVE);
                    questionTypeIdNameBean = null;
                    selectQuestionTypeTv.setText(NEGATIVE);
                    difficultyIdNameBean = null;
                    selectDifficultyTv.setText(NEGATIVE);

                } else if (pickType == PICK_TYPE_QUESTION) {
                    //选择题型
                    questionTypeIdNameBean = idNameBean;
                    selectQuestionTypeTv.setText(idNameBean.getName());
                    //将题型之后的选项清空
                    difficultyIdNameBean = null;
                    selectDifficultyTv.setText(NEGATIVE);

                } else if (pickType == PICK_TYPE_DIFFICUTY) {
                    //选择难度
                    difficultyIdNameBean = idNameBean;
                    selectDifficultyTv.setText(idNameBean.getName());

                } else if (pickType == PICK_TYPE_UNDERSTAND) {
                    //选择掌握程度
                    underStandIdNameBean = idNameBean;
                    selectUnderStandTv.setText(idNameBean.getName());
                }

                selectLayoutPop.dismiss();
            }
        });

        selectLayoutPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
//                backgroundAlpha(1.0f);
            }
        });
        selectLayoutPop.showAtLocation(getWindow().getDecorView(), Gravity.BOTTOM, 0, 0);
//        backgroundAlpha(0.5f);

    }

    /**
     * 启动题库训练页面
     *
     * @param context
     */
    public static void startTrainingSelectActivity(Context context) {
        Intent intent = new Intent();
        intent.setClass(context, TrainingSelectActivity.class);
        intent.putExtra(PARAM_TYPE, TYPE_TIKU_PRACTICE);
        context.startActivity(intent);
    }


}
